package com.weetop.cfw.utils

import com.weetop.cfw.api.Api
import com.weetop.cfw.constants.UrlConstants
import com.weetop.cfw.https.SslSocketFactory
import com.weetop.cfw.https.UnSafeTrustManager
import com.weetop.cfw.interceptor.JsonInterceptor
import com.weetop.cfw.interceptor.RetryInterceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

class RetrofitUtils {

    companion object{

        private var api:Api? = null

        /**
         * 获取OkHttpClient对象
         */
         private fun getOkHttpClient() = OkHttpClient.Builder()
             .addInterceptor(JsonInterceptor())
             .addInterceptor(RetryInterceptor(4))
             .connectTimeout(10000,TimeUnit.MILLISECONDS)
             .readTimeout(10000,TimeUnit.MILLISECONDS)
             .writeTimeout(10000,TimeUnit.MILLISECONDS)
             .retryOnConnectionFailure(true)
             .sslSocketFactory(SslSocketFactory.getSSLSocketFactory(), UnSafeTrustManager())
             .build()

        /**
         * 获取Retrofit对象
         */
        private fun getRetrofit() = Retrofit.Builder()
            .client(getOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl(UrlConstants.baseUrl)
            .build()

        /**
         * 获取Api对象
         */
        fun getApi():Api{
            if(api == null){
                api = getRetrofit().create(Api::class.java)
            }
            return api!!
        }
    }
}